package com.young.common.client.log.core;

import com.young.interfaces.log.model.LogDTO;
import com.young.interfaces.log.service.ILogHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 日志消费任务
 * Created by rookie on 2017/11/10.
 */
public class LogConsumeTask implements Runnable {

    private static final Logger logger = LoggerFactory.getLogger(LogConsumeTask.class);

    private LogDTO logDTO;//待销费的日志

    /**
     * 无参构造函数
     */
    public LogConsumeTask(){
        super();
    }

    /**
     * 带参构造函数
     * @param logDTO
     */
    public LogConsumeTask(LogDTO logDTO){
        super();
        this.logDTO = logDTO;
    }

    @Override
    public void run() {
        logDTO.setLogTime(new Date());//设置日志处理时间
        //Log log = logDTO.getLog();
        List<ILogHandler> logHandlers = new ArrayList<ILogHandler>();
        if (logDTO != null && logDTO.getLogHandler() != null && logDTO.getLogHandler().length > 0){//获取指定的日志处理器
            for (String bean : logDTO.getLogHandler()) {
                ILogHandler logHandler = LogHandlerFactory.getHandler(bean);
                if (logHandler != null) {
                    logHandlers.add(logHandler);
                }
            }
        }
        if (logHandlers == null || logHandlers.size() == 0){
            logHandlers.add(LogHandlerFactory.getDefaultHandler());//默认的日志处理器
        }
        //调用处理器的日志处理
        for (ILogHandler logHandler : logHandlers) {
            if (logHandler == null) {
                logger.warn("[日志消费任务] 该日志处理器为空,跳过.");
                continue;
            }
            try {
                logHandler.handle(logDTO);
            } catch (Exception e) {
                logger.error("[日志消费任务] 日志处理器[{}]处理日志发生异常,日志信息:{}", logHandler.toString(), logDTO, e);
            }
        }
    }
}
